package map.core.util;

import org.locationtech.jts.geom.Coordinate;
import org.locationtech.jts.geom.Envelope;

import static java.lang.Math.*;

public class CRSHelper {

    public static Coordinate lonLat2WebMercator(Coordinate lonLat){
        double x = lonLat.x *20037508.34/180;
        double y = log(Math.tan((90+lonLat.y)*PI/360))/(PI/180);
        y = y *20037508.34/180;
        return new Coordinate(x,y);
    }


    public static Envelope lonLat2WebMercator(Envelope envelope){
        Coordinate leftBottom = new Coordinate(envelope.getMinX(), envelope.getMinY());
        Coordinate rightTop = new Coordinate(envelope.getMaxX(), envelope.getMaxY());

        return new Envelope(CRSHelper.lonLat2WebMercator(leftBottom), CRSHelper.lonLat2WebMercator(rightTop));

    }


    public static Envelope webMercatorToLonLat(Envelope envelope){
        Coordinate leftBottom = new Coordinate(envelope.getMinX(), envelope.getMinY());
        Coordinate rightTop = new Coordinate(envelope.getMaxX(), envelope.getMaxY());

        return new Envelope(CRSHelper.webMercatorToLonLat(leftBottom), CRSHelper.webMercatorToLonLat(rightTop));

    }

    public static  Coordinate webMercatorToLonLat(Coordinate mercator){
        double x = mercator.x/20037508.34*180;
        double y = mercator.y/20037508.34*180;
        y= 180/PI*(2*atan(exp(y*PI/180))-PI/2);
        return new Coordinate(x,y);
    }
}
